package com.nuo.laboratory.jdk;

import org.junit.Test;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * Decimal
 *
 * @author LGC
 * @date 2022/4/11 9:23
 */
public class BigDecimalTest {

    @Test
    public void BigDecimalCreate() {
        BigDecimal a = new BigDecimal(0.1);
        System.out.println("构造参数为Double:\t" + a);
        BigDecimal b = new BigDecimal("0.1");
        System.out.println("构造参数为String:\t" + b);
        // 阿里规范也要求用String来构造
        // 构造参数为Double:0.1000000000000000055511151231257827021181583404541015625
        // 构造参数为String:0.1

        System.out.println("=================================");
        BigDecimal c = new BigDecimal("0.235").setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("ROUND_HALF_UP 四舍五入，即>=0.5向上取整:\t" + c);

        BigDecimal d = new BigDecimal("0.235").setScale(2, BigDecimal.ROUND_HALF_DOWN);
        System.out.println("ROUND_HALF_DOWN 五舍六入，即>0.5向上取整:\t" + d);

        System.out.println("=================================");
        BigDecimal zero = BigDecimal.ZERO;
        System.out.println("Zero BigDecimal:\t" + zero);

    }

    @Test
    public void BigDecimalFormat() {
        NumberFormat currency = NumberFormat.getCurrencyInstance(); //建立货币格式化引用
        NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用
        percent.setMaximumFractionDigits(3); //百分比小数点最多3位

        BigDecimal loanAmount = new BigDecimal("800000.55"); //贷款金额
        BigDecimal interestRate = new BigDecimal("0.056"); //利率
        BigDecimal interest = loanAmount.multiply(interestRate); //相乘
        BigDecimal total = loanAmount.add(interest); //相加
        System.out.println("贷款金额:\t" + currency.format(loanAmount));
        System.out.println("利率:\t" + percent.format(interestRate));
        System.out.println("利息:\t" + currency.format(interest));
        System.out.println("总金额:\t" + currency.format(total));

    }

    /**
     * 保留两位小数
     *
     * @param obj 传入的小数
     */
    public String formatToNumber(BigDecimal obj) {
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(obj);
    }

    @Test
    public void numberFormat() {
        System.out.println(formatToNumber(new BigDecimal("3.435")));
        System.out.println(formatToNumber(new BigDecimal(0)));
        System.out.println(formatToNumber(new BigDecimal("0.00")));
        System.out.println(formatToNumber(new BigDecimal("0.001")));
        System.out.println(formatToNumber(new BigDecimal("0.006")));
        System.out.println(formatToNumber(new BigDecimal("0.206")));
    }

}
